package com.ourteam.system.api;

import com.ourteam.frame.web.AbstractTreeNodeBuilder;
import com.ourteam.system.dao.ISysDepartmentDAO;
import com.ourteam.system.dao.SysDepartmentDAOQueryBean;
import com.ourteam.system.domain.SystemDepartmentBean;
import com.ourteam.system.service.ISysDepartmentService;
import com.ourteam.system.service.SysDepartmentServiceFactory;

public class SystemDepartmentNodeBuilder extends AbstractTreeNodeBuilder<SystemDepartmentBean, SystemDepartmentBean> {

	private static final ISysDepartmentService departFmentService = SysDepartmentServiceFactory
			.getSysDepartmentService();

	@Override
	public SystemDepartmentBean[] getTreeNodeObjects(SystemDepartmentBean parentObject) throws Exception {

		long parentId = parentObject != null ? parentObject.getId() : 0;

		SysDepartmentDAOQueryBean queryBean = new SysDepartmentDAOQueryBean();

		queryBean.setSortProperty(ISysDepartmentDAO.SortIndex);

		queryBean.createCriteria().andParentIdEqualTo(parentId);

		return departFmentService.querySystemDepartments(queryBean);
	}

	@Override
	public Object getNodeId(SystemDepartmentBean childObject) throws Exception {

		return childObject.getId();
	}

	public boolean isLeaf(SystemDepartmentBean childObject) throws Exception {

		long parentId = childObject.getId();

		SysDepartmentDAOQueryBean queryBean = new SysDepartmentDAOQueryBean();

		queryBean.setSortProperty(ISysDepartmentDAO.SortIndex);

		queryBean.createCriteria().andParentIdEqualTo(parentId);

		return departFmentService.querySystemDepartmentCount(queryBean) == 0;
	}

	@Override
	public String getNodeDefineId(SystemDepartmentBean childObject) throws Exception {

		return "sysDep";
	}

	@Override
	public SystemDepartmentBean converToParentObject(Object parent) throws Exception {
		if (parent == null) {
			return null;
		} else {
			return SysDepartmentServiceFactory.getSysDepartmentService()
					.getSystemDepartmentById(Long.parseLong(parent.toString()));
		}
	}

	@Override
	public int getChildCount(SystemDepartmentBean childObject) throws Exception {

		ISysDepartmentService departFmentService = SysDepartmentServiceFactory.getSysDepartmentService();

		SysDepartmentDAOQueryBean queryBean = new SysDepartmentDAOQueryBean();

		queryBean.createCriteria().andParentIdEqualTo(childObject.getId());

		return 10;// departFmentService.querySystemDepartmentCount(queryBean);

	}

}
